package activity;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.VolleyError;
import com.qzhy.female.R;

import Constant.Constance;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.speech.SpeechRecognizer;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import photopicker.ImageCaptureManager;
import photopicker.SelectModel;
import utils.FileUtils;
import utils.HTTPUtils;
import utils.SetUtils;
import volley.VolleyListener;

public class RepliesActivity extends BaseActivity implements  OnClickListener {
	public List<Bitmap> bmp = new ArrayList<Bitmap>();
	public List<String> drr = new ArrayList<String>();
	List<String> urList = new ArrayList<String>();
	private TextView mTvSend;
	private ImageView mImgVoice;
	private View speechTips;
	private ImageView mImgBack;
	private TextView mTvLog;
	private TextView mTvVoiceResult;
	private static final int EVENT_ERROR = 11;
	private EditText mEtPost;
	private View speechWave;
	private static final String TAG = "Touch";
	private Button mBtnSelPic;
	private boolean IsSel=true;
	private LinearLayout mLlPic;
	public static Bitmap bimap ;
	private GridView mGdPic;
	private GridAdapter gridAdapter;
	 private static final int REQUEST_CAMERA_CODE = 11;
	    private static final int REQUEST_PREVIEW_CODE = 22;
	    private ImageCaptureManager captureManager; // 相机拍照处理类	    
	    private ArrayList<String> imagePaths = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_replies);
		InitUI();
	}
	private void InitUI() {
		mTvSend = (TextView) findViewById(R.id.tv_send);
		mTvSend.setOnClickListener(this);
		mImgVoice = (ImageView) findViewById(R.id.img_voice);
		mImgBack = (ImageView) findViewById(R.id.img_back);
		mImgBack.setOnClickListener(this);
		mEtPost = (EditText) findViewById(R.id.et_post_text);
		mTvVoiceResult = (TextView) findViewById(R.id.tv_voice);
		mTvLog = (TextView) findViewById(R.id.tv_log);
		mBtnSelPic = (Button) findViewById(R.id.btn_sel_pic);
		mBtnSelPic.setOnClickListener(this);
		mLlPic = (LinearLayout) findViewById(R.id.ll_btn_container);
		mGdPic = (GridView) findViewById(R.id.gd_pic);
		loadAdpater();
		mGdPic.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if(position==bmp.size()){
					 PhotoPickerIntent intent = new PhotoPickerIntent(RepliesActivity.this);
		             intent.setSelectModel(SelectModel.MULTI);
		             intent.setShowCarema(true); // 是否显示拍照
		             intent.setMaxTotal(8); // 最多选择照片数量，默认为9
		             intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
		             intent.putExtra("pics", bmp.size());
		             startActivityForResult(intent, REQUEST_CAMERA_CODE);
				}else {
					Intent intent = new Intent(RepliesActivity.this,
							PhotoActivity.class);
					intent.putExtra("ID", position);
					startActivity(intent);
				}
			}
		});
	}
	
	
	private void loadAdpater(){
        if(gridAdapter == null){
             gridAdapter = new GridAdapter();
            mGdPic.setAdapter(gridAdapter);
        }else {
            gridAdapter.notifyDataSetChanged();
        }
    }

    private class GridAdapter extends BaseAdapter{
        private ArrayList<String> listUrls;
		private Button btDel;
		private ViewHolder viewHolder;

        @Override
        public int getCount() {
        	if(bmp.size() == 8){
				return 8;
			}
			return (bmp.size() + 1);
        }

        @Override
        public String getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        public class ViewHolder {
			public ImageView image;
			public Button bt;
		}

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                viewHolder = new ViewHolder();
                viewHolder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
                 viewHolder.bt = (Button) convertView
						.findViewById(R.id.item_grida_bt);
                 convertView.setTag(viewHolder);
            }else {
            	viewHolder = (ViewHolder) convertView.getTag();
            }
        	if (position ==bmp.size()) {
        		viewHolder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
        		viewHolder.bt.setVisibility(View.GONE);
        		if (position == 8) {
					viewHolder.image.setVisibility(View.GONE);
        		}
			} else {
					viewHolder.image.setImageBitmap(bmp.get(position));
					viewHolder.bt.setVisibility(View.VISIBLE);
			}
            viewHolder.bt.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					bmp.remove(position);
					loadAdpater();
				}
			});
            return convertView;
        }
    }
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 super.onActivityResult(requestCode, resultCode, data);
		 if(resultCode == RESULT_OK) {
        	 ArrayList<String> paths = new ArrayList<>();
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                	paths= data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
//                	paths= data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if(captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        paths.add(captureManager.getCurrentPhotoPath());
                    }
                    break;
            }
            for (int i = 0; i < paths.size(); i++) {
            	bmp.add(photopicker.BitmapUtils.compressImageFromFile(paths.get(i)));
            }
            loadAdpater();
        }
	}
	
	
	protected void onDestroy() {

		FileUtils.deleteDir(FileUtils.SDPATH);
		FileUtils.deleteDir(FileUtils.SDPATH1);
		// 清理图片缓存
		for (int i = 0; i < bmp.size(); i++) {
			bmp.get(i).recycle();
		}
		for (int i = 0; i < PhotoActivity.bitmap.size(); i++) {
			PhotoActivity.bitmap.get(i).recycle();
		}
		PhotoActivity.bitmap.clear();
		bmp.clear();
		drr.clear();
		super.onDestroy();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_send:
			Send();
			break;
		case R.id.img_back:
			finish();
			break;	
		case R.id.btn_sel_pic:
			if(IsSel){
				mLlPic.setVisibility(View.VISIBLE);
			}else {
				mLlPic.setVisibility(View.GONE);
			}
			IsSel=!IsSel;
			break;
		default:
			break;
		}
	}
	private void Send(){
		showLoadingDialog();
		Toast.makeText(getApplicationContext(), "发送图片的个数"+bmp.size()+"用户Id:"+SetUtils.GetUserId(getApplicationContext()), Toast.LENGTH_LONG).show();
		Map<String, String> params=new HashMap<String,String>();
		params.put("user_id",""+SetUtils.GetUserId(getApplicationContext()));
		params.put("category_id", ""+SetUtils.GetCircleID(getApplicationContext()));
		params.put("title", "test");
		params.put("imgSize", ""+bmp.size());
		params.put("content", mEtPost.getText().toString().trim());
		for (int i = 0; i < bmp.size(); i++) {
			params.put("photo"+i, Bm_St(bmp.get(i)));
		}
		HTTPUtils.post(getApplicationContext(), Constance.URL.POST_ARTICLE, params, new VolleyListener() {
			@Override
			public void onResponse(String arg0) {
//				Toast.makeText(getApplicationContext(), "onResponse"+arg0.toString(), 1).show();
				if(arg0!=null){
					dismissLoadingDialog();
					Intent intent = new Intent();
					setResult(12, intent);
					finish();
				}
			}
			
			@Override
			public void onErrorResponse(VolleyError arg0) {
				Toast.makeText(getApplicationContext(), "解析错误",1).show();
			}
		});
	}
	/**

	 * 上传图片到服务端

	 */
	    private String Bm_St(Bitmap bitmap){
	        ByteArrayOutputStream stream = new ByteArrayOutputStream();
	        bitmap.compress(CompressFormat.PNG, 60, stream);
	        byte[] byteArray = stream.toByteArray();
	        String img = new String(Base64.encodeToString(byteArray, Base64.DEFAULT)); 
	        return img;
	    }
	
}